package sunyu.demo.spring.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import sunyu.toolkit.core.LogKit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * TCP服务端程序入口
 *
 * @author 孙宇
 */
@Component
public class NettyTcpBootstrap {

    private static final Logger logger = LogKit.getLogger();

    /**
     * 服务端监听的端口地址
     */
    private static final int port = 7878;
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    @Resource
    private TcpChannelInitializer tcpChannelInitializer;

    @PostConstruct
    public void init() throws InterruptedException {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(tcpChannelInitializer);

        // 服务器绑定端口监听
        ChannelFuture f = b.bind(port).sync();
        // 监听服务器关闭监听
        f.channel().closeFuture().sync();

        // 可以简写为
        //b.bind(port).sync().channel().closeFuture().sync();
    }

    @PreDestroy
    public void shutdown() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
